package cn.easier.activity.console.service.impl;

import cn.easier.activity.console.repository.ActivityInfoRepository;
import cn.easier.activity.console.repository.PrizeClawImageMessageRepository;
import cn.easier.activity.console.service.ActivityInfoService;
import cn.easier.activity.web.entity.ActivityInfo;
import cn.easier.activity.web.entity.PrizeClawImageMessage;
import cn.easier.club.base.dto.ResultInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 活动信息ServiceImpl
 */
@Service
@Transactional
public class ActivityInfoServiceImpl implements ActivityInfoService {

    private static Logger logger = LoggerFactory.getLogger(ActivityInfoServiceImpl.class);

    //活动状态
    private static final Integer RELEASE_STATE = 1;
    private static final Integer DELETE_STATE = 2;

    @Autowired
    ActivityInfoRepository activityInfoRepository;

    @Autowired
    PrizeClawImageMessageRepository prizeClawImageMessageRepository;

    @Override
    public ResultInfo findPage(String user, Integer pageIndex, Integer pageNum, String name, String title, Integer templateInfoId) {
        Pageable pageable = new PageRequest(pageIndex - 1, pageNum, new Sort(Sort.Direction.DESC, "createTime"));

        //条件组织
        Specification<ActivityInfo> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(name)) {
                predicates.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
            }
            if (StringUtils.isNotBlank(title)) {
                predicates.add(cb.like(root.get("title").as(String.class), "%" + title + "%"));
            }
            if (templateInfoId != null && templateInfoId > 0) {
                predicates.add(cb.equal(root.get("templateInfoId").as(Integer.class), templateInfoId));
            }
            predicates.add(cb.equal(root.get("createBy").as(String.class), user));
            predicates.add(cb.notEqual(root.get("status").as(String.class), 2));
            Predicate[] p = new Predicate[predicates.size()];
            return cb.and(predicates.toArray(p));
        };

        //多条件查询
        Page<ActivityInfo> page = activityInfoRepository.findAll(spec, pageable);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                String.valueOf(page.getTotalElements()), page.getContent());
    }

    @Override
    public ResultInfo findAllActivity(Integer pageIndex, Integer pageNum, String name, String title, Integer templateInfoId) {
        Pageable pageable = new PageRequest(pageIndex - 1, pageNum);//, new Sort(Sort.Direction.DESC, "createTime")
        /*
         * //条件组织 Specification<ActivityInfo> spec = new Specification<ActivityInfo>() {
         *
         * @Override public Predicate toPredicate(Root<ActivityInfo> root,
         * CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicates =
         * new ArrayList<>();
         * predicates.add(cb.notEqual(root.get("status").as(String.class), "2"));
         * Predicate[] p = new Predicate[predicates.size()]; Predicate predicate =
         * cb.and(predicates.toArray(p)); return predicate; } }; Page<ActivityInfo> page
         * = activityInfoRepository.findAll(spec, pageable);
         */
        Page<ActivityInfo> page = activityInfoRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(name)) {
                predicates.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
            }
            if (StringUtils.isNotBlank(title)) {
                predicates.add(cb.like(root.get("title").as(String.class), "%" + title + "%"));
            }
            if (templateInfoId != null && templateInfoId > 0) {
                predicates.add(cb.equal(root.get("templateInfoId").as(Integer.class), templateInfoId));
            }
            predicates.add(cb.notEqual(root.get("status").as(String.class), "2"));
            query.orderBy(cb.desc(root.get("id")));
            Predicate[] p = new Predicate[predicates.size()];
            return cb.and(predicates.toArray(p));
        }, pageable);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                String.valueOf(page.getTotalElements()), page.getContent());
    }

    @Override
    public ActivityInfo findOne(Integer id, String user) {
        return activityInfoRepository.findOne(id, user);
    }

    @Override
    public ActivityInfo save(ActivityInfo activityInfo) {
        return activityInfoRepository.save(activityInfo);
    }

    @Override
    public ActivityInfo update(ActivityInfo activityInfo) {
        // advancedSetting 增量更新，避免保存时覆盖已有属性
        String advancedSetting = activityInfo.getAdvancedSetting();
        if (StringUtils.isNotBlank(advancedSetting)) {
            JSONObject advancedConfigJson = JSON.parseObject(advancedSetting);
            Optional<ActivityInfo> optionalActivityInfo = activityInfoRepository.findById(activityInfo.getId());
            if (optionalActivityInfo.isPresent()) {
                ActivityInfo info = optionalActivityInfo.get();
                String setting = info.getAdvancedSetting();
                if (StringUtils.isNotBlank(setting)) {
                    JSONObject configJson = JSON.parseObject(setting);
                    // 只更新传过来的属性
                    configJson.putAll(advancedConfigJson);
                    activityInfo.setAdvancedSetting(configJson.toJSONString());
                }
            }
        }
        return activityInfoRepository.saveAndFlush(activityInfo);
    }

    @Override
    public boolean release(String foregroundLink, Integer id, String user) {
        int changeNum = activityInfoRepository.release(RELEASE_STATE, foregroundLink, id, user);
        return changeNum > 0 ? true : false;
    }

    @Override
    public boolean runOrPause(Boolean release, Integer id, String user) {
        int changeNum = activityInfoRepository.runOrPause(release, id, user);
        return changeNum > 0 ? true : false;
    }

    @Override
    public boolean runOrPauseOrSuperUser(Boolean release, Integer id) {
        int changeNum = activityInfoRepository.runOrPauseOrSuperUser(release, id);
        return changeNum > 0 ? true : false;
    }

    @Override
    public boolean delete(Integer id, String user) {
        int changeNum = activityInfoRepository.delete(DELETE_STATE, id, user);
        return changeNum > 0 ? true : false;
    }

    @Override
    public List<Integer> getHottest(Integer top) {
        return activityInfoRepository.getHottest(top);
    }

    @Override
    public List<ActivityInfo> findAll(String user) {
        return activityInfoRepository.findActivityInfosByCreateByAndStatusNotOrderByCreateTimeDesc(user, 2);
    }

    @Override
    public ActivityInfo findInfo(Integer activityPrizeId) {
        return activityInfoRepository.findInfo(activityPrizeId);
    }

    @Override
    public ActivityInfo findByOne(Integer id) {
        return activityInfoRepository.findByOne(id);
    }

    @Override
    public Boolean deleteSuper(Integer id) {
        int changeNum = activityInfoRepository.deleteSuper(DELETE_STATE, id);
        return changeNum > 0 ? true : false;
    }

    @Override
    public ActivityInfo findByInfo(String user, Integer activityPrizeId) {
        return activityInfoRepository.findByInfo(user, activityPrizeId);
    }

    @Override
    public List<ActivityInfo> findNewAll() {
        return activityInfoRepository.findByStatusNotOrderByCreateTimeDesc(2);
    }

    @Override
    public ResultInfo savePrizeClawImageMessage(Integer activityInfoId, PrizeClawImageMessage prizeClawImageMessage) {
        try {
            PrizeClawImageMessage one = prizeClawImageMessageRepository.findAllByActivityInfoId(activityInfoId);
            if (one == null) {
                prizeClawImageMessage.setCreateTime(new Date());
                prizeClawImageMessage.setActivityInfoId(activityInfoId);
                PrizeClawImageMessage save = prizeClawImageMessageRepository.save(prizeClawImageMessage);
                logger.info("保存成功", save);
                return new ResultInfo(String.valueOf(HttpStatus.SC_OK), "保存成功", save);
            } else {
                one.setPrimaryButtonImage(prizeClawImageMessage.getPrimaryButtonImage());
                one.setAdvancedButtonImage(prizeClawImageMessage.getAdvancedButtonImage());
                one.setStartButtonImage(prizeClawImageMessage.getStartButtonImage());
                one.setActivityRuleImage(prizeClawImageMessage.getActivityRuleImage());
                one.setAdvancedButtonImage(prizeClawImageMessage.getAdvancedButtonImage());
                one.setFrameImage(prizeClawImageMessage.getFrameImage());
                one.setDismantlingDollsImage(prizeClawImageMessage.getDismantlingDollsImage());
                one.setParticipationRecordImage(prizeClawImageMessage.getParticipationRecordImage());
                one.setLittleBackgroundImage(prizeClawImageMessage.getLittleBackgroundImage());
                one.setBigBackgroundImage(prizeClawImageMessage.getBigBackgroundImage());
                one.setDollStyles(prizeClawImageMessage.getDollStyles());
                one.setHorseRaceLampImage(prizeClawImageMessage.getHorseRaceLampImage());
                logger.info("修改成功", one);
                return new ResultInfo(String.valueOf(HttpStatus.SC_OK), "保存成功", one);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存抓娃娃活动高级设置图片失败,activityInfoId:=>{}", e, activityInfoId);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "保存抓娃娃活动高级设置图片失败", null);
        }
    }
}
